﻿using BillingExceptions;
using System;
using System.Data.SqlClient;
using System.IO;
using System.Text;

namespace Billing
{
    class ServiceData
    {
        /// <summary>
        /// Загружается экземпляр класса. Синглетон
        /// </summary>
        public static ServiceData Item
        {
            get
            {
                if (_item == null)
                {
                    lock (_syncRoot)
                    {
                        if (_item == null)
                            _item = new ServiceData();
                    }
                }
                return _item;
            }
        }

        /// <summary>
        /// Проверяются данные переданного класса на корректность
        /// </summary>
        /// <param name="bs">Класс содержащий данные для настройки соединения с сервером и пути к файлам</param>
        public static void Check(BillingSettings bs)
        {
            ServiceData.Item._error.Length = 0;
            
            ServiceData.Item.CheckDbConnection(bs);
            ServiceData.Item.CheckPathToCatalog(bs);
            ServiceData.Item.CheckPathToArchive(bs);

            if (ServiceData.Item._error.Length > 0)
                throw new BException(ErrType.Message, ServiceData.Item._error.ToString());
        }

        #region Private

        private void CheckDbConnection(BillingSettings bs)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder()
            {
                UserID = bs.Login,
                Password = bs.Password,
                DataSource = bs.ServerName,
                InitialCatalog = bs.DbName,
                IntegratedSecurity = bs.IsWindowsAuthentification
            };
            using (var conn = new SqlConnection(builder.ConnectionString))
            {
                try
                {
                    conn.Open();
                }
                catch (Exception err)
                {
                    _error.Append(err.Message + "\r");
                }
            }
        }
        private void CheckPathToCatalog(BillingSettings bs)
        { 
            if (!Directory.Exists(bs.PathToCatalog))
                _error.Append(String.Format(Properties.Resources.NotExistSaveDirectory, bs.PathToCatalog) + "\r");
        }
        private void CheckPathToArchive(BillingSettings bs)
        {
            if (!Directory.Exists(bs.PathToArchive))
                _error.Append(String.Format(Properties.Resources.NotExistArchiveDirectory, bs.PathToArchive) + "\r");
        }

        private ServiceData() { }
        private static ServiceData _item;
        private static object _syncRoot = new Object();
        private StringBuilder _error = new StringBuilder();

        #endregion
    }
}
